package control

import (
	"context"
	"fmt"
	"dockerui/models"
	ut "dockerui/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	"github.com/fatih/structs"
	"time"
)

func dockerNetworks(skip int, limit int, search string) ([]models.NetworksFormatResp, int, error) {
	var (
		client *client.Client
		ctx context.Context
		cancel context.CancelFunc
		err error
		networkOpt *types.NetworkListOptions
		networkMap map[string]interface{}
		networkResp []map[string]interface{}
		networks []types.NetworkResource
		networkFormatResp []models.NetworksFormatResp
		verifiedSkip int
		verifiedLimit int
	)
	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client = ut.GClient

	networkFilters := filters.NewArgs()
	if search == "" {
		networkFilters.Add("name", "")
	}else {
		networkFilters.Add("name", search)
	}
	networkOpt = &types.NetworkListOptions{
		Filters: networkFilters,
	}
	if networks, err = client.NetworkList(ctx, *networkOpt); err != nil {
		return nil, 0, err
	} else {
		for _, network := range networks {
			networkMap = structs.Map(&network)
			networkResp = append(networkResp, networkMap)
		}
	}
	networkFormatResp = ut.FormatNetworkList(networkResp)
	verifiedSkip, verifiedLimit = ut.LimitVerify(skip, limit, len(networkFormatResp))
	return networkFormatResp[verifiedSkip:verifiedLimit], len(networkFormatResp), nil
}

func dockerNetworkInspect(networkId string, networkScope string, networkVerbose bool) (map[string]interface{}, int, error){
	var (
		client *client.Client
		ctx context.Context
		cancel context.CancelFunc
		err error
		networkOption types.NetworkInspectOptions
		networkInspect types.NetworkResource
		networkInspectResp map[string]interface{}
	)

	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client = ut.GClient

	networkOption = types.NetworkInspectOptions{
		Scope: networkScope,
		Verbose: networkVerbose,
	}

	if networkInspect, err = client.NetworkInspect(ctx, networkId, networkOption); err != nil {
		fmt.Println("inspect network err!", err)
		return nil, 0, err
	} else {
		networkInspectResp = structs.Map(networkInspect)
		return networkInspectResp, 1, nil
	}
}